define([
    'jquery',
    'baseUtils',
    'base',
    'msgTool',
    'print',
    'plugins/bootstrap-table/bootstrap-table',
    "plugins/bootstrap-dialog/bootstrap-dialog",
    "css!global/plugins/bootstrap-dialog/bootstrap-dialog.css"
], function ($, baseUtils, base, msgTool, print, _, BootstrapDialog) {
    //默认加载基础库
    base();

    /**
     * 打印证件
     * @param idCardNo  身份证号码
     * @param row  提交的数据
     */
    function printBox(idCardNo, row) {
        BootstrapDialog.show({
            type: BootstrapDialog.TYPE_DEFAULT,
            title: "打印证件",
            closeByBackdrop: false,
            message: $('<div></div>').load("/start/print/" + idCardNo + "/" + row.id),
            data: {
                'row': row
            },
            buttons: [{
                label: '关闭窗口',
                cssClass: 'btn-white cancel',
                action: function (dialog) {
                    dialog.close();
                }
            }],
            onshown: function (dialogRef) {
                $("#dialog").val(dialogRef.options.id);
            }
        });
    }


    /**
     * 身份证扫描
     */
    return {
        scan: function () {
            //身份证信息
            var IdCardInfo;
            /**
             * 实际执行方法
             */
            if (window.isAIO !== undefined && window.isAIO) {
                // 读取身份证
                readIdCard();
                // 打印身份证
                $("#printIdCard").on('click', function () {
                    var submit = $(this);
                    $.ajax({
                        url: "/start/print/check/" + IdCardInfo.idCardNo,
                        type: "POST",
                        beforeSend: function () {
                            //触发ajax请求开始时执行
                            submit.find("b").text("打印中...");
                            submit.attr('disabled', 'disabled');
                        },
                        success: function (data) {
                            if (data.success) {
                                printIdCard(IdCardInfo);
                            } else {
                                msgTool.error("身份证号码：" + IdCardInfo.idCardNo + "已超出每日打印限额（1张）！");
                            }
                        },
                        error: function () {
                            msgTool.error("操作失败，请重新识别身份证！");
                        },
                        complete: function () {
                            submit.find("b").text("打印身份证");
                            submit.removeAttr('disabled');
                        }
                    });
                });
                // 个人证明办理
                $("#getPersonalCert").on('click', function () {
                    getPersonalCert(IdCardInfo);
                });
                // 企业证件领取
                $("#getCompanyCert").on('click', function () {
                    window.location = '/start/list/' + $("#idCardNo").val();
                });
            } else {
                msgTool.error('当前不是一体机环境！', "错误提示");
            }

            /**
             * 读取身份证
             */
            function readIdCard() {
                send_command(
                    "idReaderReadInfo",
                    "nothing",
                    function (receivedData) {
                        IdCardInfo = JSON.parse(receivedData);
                        if (IdCardInfo.status === 100) {
                            msgTool.success('身份证读取成功', "提示");
                            //充填数据
                            fillData(IdCardInfo);
                            //记录数据
                            localStorage.setItem("userName", IdCardInfo.name);
                            localStorage.setItem("userIdCard", IdCardInfo.idCardNo);
                            //停止读取
                            stopIdCard();
                            //隐藏身份证提示框
                            $("#idCardTips").hide(1000);
                            //核实身份证信息
                            $("#idCardInfo").show(1000);
                        } else if (IdCardInfo.status === 200) {
                            msgTool.error('身份证连接错误！请重试！', "错误提示");
                            return false;
                        } else if (IdCardInfo.status === 300) {
                            msgTool.error('模块未开启', "错误提示");
                            return false;
                        }
                    });

            }

            /**
             * 打印身份证
             */
            function printIdCard(IdCardInfo) {
                if (IdCardInfo === '') {
                    msgTool.error('身份证信息读取失败', "错误");
                    return;
                }
                var idImgCode = IdCardInfo.A4Img;
                if (idImgCode !== '') {
                    //Toast('', '打印身份证');
                    var photo = {
                        "Num": 1,
                        "Imgstr": idImgCode.replace(" "),
                        "ChoiceTray": 5,
                        "ChoicePaper": 0
                    };
                    var data = JSON.stringify(photo);
                    send_command(
                        "printBitmap",
                        data,
                        function (receivedData) {
                            var info = JSON.parse(receivedData);
                            if (info.status === 100) {
                                msgTool.success('身份证打印成功', "提示");
                            } else if (info.status === 300) {
                                msgTool.error('打印模块未开启！', "错误提示");
                            } else {
                                msgTool.error('身份证打印失败：' + info.msg, "错误提示");
                            }
                        });
                } else {
                    msgTool.error('未找到身份证文件', "错误提示");
                }
            }

            /**
             * 打印个人证明
             * 跳转之前，保存身份证信息
             */
            function getPersonalCert(IdCardInfo) {
                var submit = $("#getPersonalCert");
                IdCardInfo.status=1;//读卡器给的状态是100，数据库存状态为1；
                $.ajax({
                    url: "/personal/save",
                    type: "POST",
                    data: IdCardInfo,
                    beforeSend: function () {
                        //触发ajax请求开始时执行
                        $(submit).find("b").text("提交中...");
                        $(submit).attr('disabled', 'disabled');
                    },
                    success: function (data) {
                        if (data.success) {
                            //跳转
                            window.location = "../personal/list/" + IdCardInfo.idCardNo;
                        } else {
                            msgTool.error(data.msg);
                        }
                    },
                    error: function () {
                        msgTool.error("操作失败，请退出系统后重试！");
                    },
                    complete: function () {
                        $(submit).find("b").text("个人证明办理");
                        $(submit).removeAttr('disabled');
                    }
                });
            }


            /**
             * 离开关闭身份证读卡器
             */
            function stopIdCard() {
                send_command(
                    "stopRead",
                    "nothing",
                    function (receivedData) {
                        var info = JSON.parse(receivedData);
                        if (info.status === 100) {
                            //Toast('res', '身份证模块关闭成功');
                        } else if (info.status === 300) {
                            Toast('errs', '身份证模块未开启！');
                        } else {
                            Toast('err', '身份证模块关闭失败：' + info.msg);
                            alert('身份证模块关闭失败：' + info.msg);
                        }
                    });
            }


            /**
             * 充填数据
             */
            function fillData(idInfo) {
                $("#name").val(idInfo.name);
                $("#nation").val(idInfo.nation);
                $("#address").val(idInfo.address);
                $("#birthday").val(idInfo.birthday.replace(/^(\d{4})(\d{2})(\d{2})$/, "$1-$2-$3"));
                $("#sex").val(idInfo.sex);
                $("#idCardNo").val(idInfo.idCardNo);
                $("#idImg").html("<img id='idImgCode' src=\"data:image/jpeg;base64," + idInfo.idImg + "\"  class=\"img-thumbnail\" style='width: 220px;'>");
            }
        },


        /**
         * 打印列表
         */
        list: function (idCardNo) {
            var API_URL = "/start/list/" + idCardNo + "/api";
            var myTable = $('#dataList');
            var tableRefresh = function () {
                myTable.bootstrapTable('refresh', {url: API_URL})
            };


            //table当前行的响应事件
            window.operateEvents = {
                'click #printCert': function (e, value, row) {
                    printBox(idCardNo, row);
                    tableRefresh();
                }
            };


            //table表格
            myTable.bootstrapTable({
                url: API_URL, // 接口 URL 地址
                cache: false, // 不缓存
                striped: true, // 隔行加亮
                pagination: true, // 开启分页功能
                sidePagination: 'server',//服务端分页
                sortOrder: 'desc', // 设置排序为反序 desc
                fixedColumns: true,//自动修复
                queryParams: queryParams,//搜索附加参数
                smartDisplay: false, // 智能显示 pagination 和 cardview 等
                toolbar: ".toolBar", //顶部工具菜单
                toolbarAlign: "right", //顶部工具位置
                mobileResponsive: "true", //手机模式自适应宽度（自动变成卡片模式）
                columns: [
                    {
                        field: 'itemTypeValue',
                        title: '事项类型'
                    },
                    {
                        field: 'itemName',
                        title: '事项名称',
                        width: '30%'
                    },
                    {
                        field: 'issueDatetime',
                        title: '发证时间',
                        align: 'center'
                    },
                    {
                        field: 'receiveUserName',
                        title: '领取人',
                        align: 'center'
                    }, {
                        field: 'receiveDatetime',
                        title: '领取时间',
                        align: 'center'
                    }, {
                        field: 'receiveStatus',
                        title: '领取状态',
                        align: 'center',
                        width: '10%',
                        events: operateEvents,
                        formatter: function (value, row) {
                            if (value === 1) {
                                return "<span class=\"btn btn-default disabled\">" +
                                    "<i class=\"iconfont icon-dayin\" aria-hidden=\"true\"></i>&nbsp;已打印领取" +
                                    "</span>";
                            } else {
                                // return "<a href='/start/print/" + idCardNo + "/" + row.id + "' id=\"printCert\" class=\"btn btn-success\">" +
                                //     "<i class=\"iconfont icon-dayin\" aria-hidden=\"true\"></i>&nbsp;打印证件" +
                                //     "</a>";
                                return "<button id=\"printCert\" class=\"btn btn-success\"><i class=\"iconfont icon-dayin\" aria-hidden=\"true\"></i>&nbsp;打印证件</button>";
                            }
                        }
                    }
                ]
            });


            //搜索刷新
            $('#search').on('click', function () {
                tableRefresh();
            });

            //搜索参数传递
            function queryParams(params) {
                params.search = $(".searchValue").val().trim();
                return {
                    limit: params.limit,
                    offset: params.offset,
                    search: params.search
                };
            }

            //回显
            function responseHandler(res) {
                return res.rows;
            }
        },
        suggest: function () {

        }

    };
});
